<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="菜单名称" prop="menuName">
          <common-input
            v-model="queryParams.menuName"
            placeholder="请输入"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="菜单状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <common-table
      v-loading="loading"
      isSetRowKey
      :data="menuList"
      row-key="menuId"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column
        prop="menuName"
        label="菜单名称"
        width="200"
      ></el-table-column>
      <el-table-column prop="icon" label="图标" align="left" width="100">
        <template slot-scope="scope">
          <i :class="scope.row.icon"></i>
        </template>
      </el-table-column>
      <el-table-column
        prop="orderNum"
        label="排序"
        width="60"
      ></el-table-column>
      <el-table-column prop="perms" label="权限标识"></el-table-column>
      <el-table-column prop="component" label="组件路径"></el-table-column>
      <el-table-column prop="status" label="菜单状态" width="120">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === '0'">显示</el-tag>
          <el-tag type="danger" v-else>隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            >新增</el-button
          >
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </common-table>

    <!-- 添加或编辑菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="上级菜单">
              <treeselect
                v-model="form.parentId"
                :options="menuOptions"
                :normalizer="normalizer"
                :show-count="true"
                placeholder="选择上级菜单"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType">
                <el-radio label="M">目录</el-radio>
                <el-radio label="C">菜单</el-radio>
                <el-radio label="F">按钮</el-radio>
                <el-radio label="V">看板</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item v-if="form.menuType != 'F'" label="菜单图标">
              <!-- <el-popover
                placement="bottom-start"
                width="460"
                trigger="click"
                @show="$refs['iconSelect'].reset()"
              > -->
              <!-- <IconSelect ref="iconSelect" @selected="selected" /> -->
              <common-input v-model="form.icon" placeholder="请输入图标名称">
                <svg-icon
                  v-if="form.icon"
                  slot="prefix"
                  :icon-class="form.icon"
                  class="el-input__icon"
                  style="height: 32px; width: 16px"
                />
                <i v-else slot="prefix" class="el-icon-search el-input__icon" />
              </common-input>
              <!-- </el-popover> -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <common-input
                v-model="form.menuName"
                placeholder="请输入菜单名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <common-input-number
                style="width: 100%"
                :max-length="2"
                v-model="form.orderNum"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'V'">
            <el-form-item v-if="form.menuType != 'F'" label="是否外链">
              <el-radio-group v-model="form.isFrame">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              v-if="form.menuType != 'F'"
              label="路由地址"
              prop="path"
            >
              <common-input v-model="form.path" placeholder="请输入路由地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType != 'V'">
            <el-form-item v-if="form.menuType != 'F'" label="重定向地址">
              <common-input
                v-model="form.redirect"
                placeholder="请输入重定向地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType == 'C'">
            <el-form-item label="组件路径" prop="component">
              <common-input
                v-model="form.component"
                placeholder="请输入组件路径"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType !== 'V'">
            <el-form-item v-if="form.menuType != 'M'" label="权限标识">
              <common-input
                v-model="form.perms"
                placeholder="请权限标识"
                :maxlength="50"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType !== 'V'">
            <el-form-item v-if="form.menuType != 'F'" label="显示状态">
              <el-radio-group v-model="form.visible">
                <el-radio label="0">显示</el-radio>
                <el-radio label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.menuType !== 'V'">
            <el-form-item v-if="form.menuType != 'F'" label="菜单状态">
              <el-radio-group v-model="form.status">
                <el-radio label="0">显示</el-radio>
                <el-radio label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="form.menuType == 'C'" label="是否缓存">
              <el-radio-group v-model="form.isCache">
                <el-radio label="0">缓存</el-radio>
                <el-radio label="1">不缓存</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item v-if="form.menuType === 'V'" label="看板分类">
              <el-cascader
                :clearable="false"
                :options="boardList"
                v-model="form.parameter"
                :show-all-levels="false"
                collapse-tags
                :props="{ multiple: true, emitPath: false }"
                @change="changeValue"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </common-list>
</template>

<script>
import {
  listMenu,
  getMenu,
  delMenu,
  addMenu,
  updateMenu,
} from "@/api/system/menu";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import IconSelect from "@/components/IconSelect";
import { getAllTree } from "@/api/screenConfig/viewboard";
import { mapGetters } from "vuex";

export default {
  name: "Menu",
  components: { Treeselect, IconSelect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示查询条件
      showSearch: true,
      // 菜单表格树数据
      menuList: [],
      // 菜单树选项
      menuOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示状态数据字典
      visibleOptions: [],
      // 菜单状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        menuName: undefined,
        visible: undefined,
      },
      boardList: [],
      boardOptions: [],
      // 表单参数
      form: {},
      selectedBoard: "",
      // 表单校验
      rules: {
        menuName: [
          {
            required: true,
            message: "请输入菜单名称",
            trigger: "blur",
          },
        ],
        orderNum: [
          {
            required: true,
            message: "请输入菜单顺序",
            trigger: "blur",
          },
          {
            type: "number",
            min: 1,
            max: 99,
            message: "排序范围1-99",
            trigger: "blur",
          },
        ],
        path: [
          {
            required: true,
            message: "请输入路由地址",
            trigger: "blur",
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["isAdmin"]),
  },
  created() {
    if (this.isAdmin) {
      this.getList();
      this.queryAllTree();
    } else {
      this.$router.push("/404");
    }
  },
  methods: {
    //获取菜单分类数据
    queryAllTree() {
      getAllTree({ status: 0 })
        .then((res) => {
          if (res && res.code === 200) {
            this.boardList = [
              {
                id: "1",
                name: "预定义", // 名称
                isDefault: 1, // 1 预定义 0 自定义
                leaf: false, // false 分类 true 数据集
                isRoot: true,
                children: res.data.filter((item) => item.isDefault === 1),
              },
              {
                id: "0",
                name: "自定义",
                isDefault: 0,
                leaf: false,
                isRoot: true,
                children: res.data.filter((item) => item.isDefault === 0),
              },
            ];
            this.getTreeNewData([this.boardList[0]]);
            this.getTreeNewData([this.boardList[1]]);
            console.log(this.boardList);
          } else {
            this.boardList = [];
          }
        })
        .catch((err) => {
          this.boardList = [];
        });
    },

    getTreeNewData(arr) {
      arr.forEach((item) => {
        item.label = item.name;
        item.value = item.id;
        if (item.children && item.children.length > 0) {
          this.getTreeNewData(item.children);
        } else {
          if (!item.leaf) {
            item.isDisabled = true;
          } else {
            delete item.children;
          }
        }
      });
    },

    changeValue(val) {
      this.selectedBoard = val.join();
    },

    // 选择图标
    selected(name) {
      this.form.icon = name;
    },
    /** 查询菜单列表 */
    getList() {
      this.loading = true;
      listMenu(this.queryParams).then((response) => {
        response.data.forEach((item) => {
          if (item.icon === null) {
            item.icon = "";
          }
        });

        this.menuList = this.handleTree(response.data, "menuId");
        this.loading = false;
      });
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children,
      };
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
      listMenu().then((response) => {
        this.menuOptions = [];
        const menu = { menuId: 0, menuName: "主类目", children: [] };
        menu.children = this.handleTree(response.data, "menuId");
        this.menuOptions.push(menu);
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        menuId: undefined,
        parentId: 0,
        menuName: undefined,
        icon: undefined,
        menuType: "M",
        orderNum: undefined,
        isFrame: "1",
        isCache: "0",
        visible: "0",
        status: "0",
        parameter: [],
      };
      //   this.resetForm("form");
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.menuId) {
        this.form.parentId = row.menuId;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "新增菜单";
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      getMenu({ menuId: row.menuId }).then((response) => {
        this.form = response.data;
        this.form.orderNum = +response.data.orderNum;
        if (this.form.menuType === "V") {
          this.form.parameter =
            this.form.parameter && this.form.parameter.split(",");
        }
        this.open = true;
        this.title = "编辑菜单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.parameter = this.selectedBoard;
          if (this.form.menuType === "V") {
            this.form.component = "system/viewBoard/index";
          }
          if (this.form.menuId != undefined) {
            updateMenu(this.form)
              .then((response) => {
                this.$GlobalSuccessMessage("编辑成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {});
          } else {
            addMenu(this.form)
              .then((response) => {
                this.$GlobalSuccessMessage("新增成功");
                this.open = false;
                this.getList();
              })
              .catch(() => {});
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(
        '是否确认删除名称为"' + row.menuName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delMenu({
            ids: row.menuId,
          });
        })
        .then((res) => {
          if (res && res.code === 200) {
            this.getList();
            this.$GlobalSuccessMessage("删除成功");
          } else {
            this.$GlobalErrorConfirm("删除失败", res.msg);
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .vue-treeselect__multi-value {
  margin-bottom: 0;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  line-height: 28px;
  .vue-treeselect__multi-value-item-container {
    line-height: 24px;
    font-size: 14px;
    margin: 2px 0 2px 6px;
    padding: 0;
  }

  .vue-treeselect__multi-value-item {
    background-color: #f4f4f5;
    border-color: #e9e9eb;
    color: #909399;
    display: flex;
    align-items: center;
    padding-right: 1px;

    .vue-treeselect__value-remove {
      width: 12px !important;
      height: 12px !important;
      margin-right: 3px;
      color: #fff;
      border-left: none;
      background-color: #c0c4cc;
      border-radius: 50%;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0;

      &:hover {
        background-color: #909399;
      }
    }
  }
  .vue-treeselect__input-container {
    padding-top: 0 !important;
  }
}
.el-cascader {
  width: 100%;
}
</style>
